package com.schooleducation.controller.admin;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin")
public class AdminHomeController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;

	/**
	 * 获取管理员后台主页
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getHomePage(HttpSession session) {
		User user = (User) session.getAttribute("admin");
		if (user != null) {
			return "admin/index";
		} else {
			return "redirect:login";
		}
	}

	/**
	 * 更改管理员密码
	 * @param session
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value = "changePassword", method = RequestMethod.POST)
	@ResponseBody
	public String changePassword(HttpSession session, String oldPassword, String newPassword) {
		User user = (User) session.getAttribute("admin");
		Map<String, String> state = new HashMap<String, String>();
		if (serviceFac.getUserService().changePassword(user, oldPassword, newPassword)) {
			session.setAttribute("admin", user);
			state.put("update", "success");
		} else {
			state.put("update", "fail");
		}
		return JSONObject.fromObject(state).toString();
	}
}
